package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.templates.L1MapsLimitTime;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class MapsGroupTable {
  private static final Log _log = LogFactory.getLog(MapsGroupTable.class);
  
  private static final Map<Integer, L1MapsLimitTime> _mapsGroup = new HashMap<>();
  
  private static MapsGroupTable _instance;
  
  public static MapsGroupTable get() {
    if (_instance == null)
      _instance = new MapsGroupTable(); 
    return _instance;
  }
  
  public void reload() {
    _mapsGroup.clear();
    load();
  }
  
  public void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection con = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("SELECT * FROM `mapids_group` ORDER BY order_id DESC");
      rs = pstm.executeQuery();
      while (rs.next()) {
        int order_id = rs.getInt("order_id");
        String mapIds = rs.getString("mapids");
        String mapName = rs.getString("name");
        int limitTime = rs.getInt("time");
        int outMapX = rs.getInt("out_x");
        int outMapY = rs.getInt("out_y");
        short outMapId = rs.getShort("out_map");
        List<Integer> mapList = new ArrayList<>();
        String[] split;
        int length = (split = mapIds.split(",")).length;
        int i = 0;
        while (i < length) {
          String map_str = split[i];
          mapList.add(Integer.valueOf(Integer.parseInt(map_str)));
          i++;
        } 
        L1MapsLimitTime mapsLimitTime = new L1MapsLimitTime(order_id, mapList, mapName, limitTime, 
            outMapX, outMapY, outMapId);
        _mapsGroup.put(Integer.valueOf(order_id), mapsLimitTime);
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(pstm);
      SQLUtil.close(con);
    } 
    _log
      .info("载入地图群组设置资料 (入场时间限制) 数量: " + _mapsGroup.size() + "(" + timer.get() + "ms)");
  }
  
  public final Map<Integer, L1MapsLimitTime> getGroupMaps() {
    return _mapsGroup;
  }
  
  public final L1MapsLimitTime findGroupMap(int mapId) {
    Iterator<L1MapsLimitTime> iterator = _mapsGroup.values().iterator();
    while (iterator.hasNext()) {
      L1MapsLimitTime mapsLimitTime = iterator.next();
      if (mapsLimitTime.getMapList().contains(Integer.valueOf(mapId)))
        return mapsLimitTime; 
    } 
    return null;
  }
}
